package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;

import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.xml.util.XmlUtil;
import com.ccp.dev.workflow.model.SysTemplate;
import com.ccp.dev.workflow.model.SysTemplates;
import com.ccp.dev.workflow.service.SysTemplateService;
import org.dom4j.Document;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * ClassDescribe:短信邮件模版管理 控制器类
 * @author :jiayueqiao
 * Date: 2019-05-24
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/sysTemplate")
@Action(ownermodel = SysAuditModelType.PROCESS_AUXILIARY)
public class SysTemplateController extends SysBaseController {

    @Resource
    private SysTemplateService sysTemplateService;


    /**
     * 跳转页面
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/list")
    @Action(description = "查看流程辅助-短信邮件模板页面",detail="查看流程辅助-短信邮件模板页面")
    public String viewList() {
        return getAutoView();
    }

    /**
     * 取得模版数据分页列表
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/list")
    @Action(description = "查询短信邮件模板列表数据",detail = "查询短信邮件模板列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData list(HttpServletRequest request){
        QueryFilter queryFilter = new QueryFilter(request);
        List<SysTemplate> sysTemplateList;
        try {
            sysTemplateList = sysTemplateService.getAll(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success", queryFilter.getPageBean().getTotalCount(), sysTemplateList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }


    /**
     * 删除模版
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/del")
    @Action(description = "删除模版", detail = "删除短信邮件模版<#if fl>成功<#else>失败</#if>：模板id包含${templateId}")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        try {
            String[] lAryId = RequestUtil.getStringAryByStr(request, "templateId");
            sysTemplateService.delByIds(lAryId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 短信邮件模板明细页面
     * @param request request
     * @param model 视图模型
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/sysTemplateGet")
    @Action(description = "查看短信邮件模板明细页面",detail="查看短信邮件模板明细页面")
    public String sysTemplateGet(HttpServletRequest request,Model model) {
        String templateId = RequestUtil.getString(request, "templateId");
        model.addAttribute("templateId",templateId);
        return getAutoView();
    }

    /**
     * 取得模版管理明细、添加、编辑
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/get")
    @Action(description = "查询短信邮件模板明细数据", detail = "查询短信邮件模板明细数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData get(HttpServletRequest request) {
        String templateId = RequestUtil.getString(request, "templateId");
        SysTemplate sysTemplate;
        try {
            if (StringUtil.isNotEmpty(templateId)) {
                sysTemplate = sysTemplateService.getOneById(templateId);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("operation.success", sysTemplate);
            } else {
                sysTemplate = new SysTemplate();
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("operation.success", sysTemplate);
            }
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 跳转添加或编辑模版管理页面
     * @param request request
     * @param model 视图模型
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/sysTemplateEdit")
    @Action(description = "查看短信邮件模板编辑页面",detail="查看短信邮件模板编辑页面")
    public String sysTemplateEdit(HttpServletRequest request,Model model) {
        String templateId = RequestUtil.getString(request, "templateId");
        model.addAttribute("templateId",templateId);
        return getAutoView();
    }

    /**
     * 设置默认
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/setDefault")
    @Action(description = "设置默认",detail="设置默认模板<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData setDefault(HttpServletRequest request){
        String templateId = RequestUtil.getString(request, "templateId");
        try {
            sysTemplateService.setDefault(templateId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success");
        } catch (Exception ex) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 添加或更新模版管理
     * @param sysTemplate 模板对象
     * @return ResultData
     */
    @RequestMapping("/save")
    @Action(
            description="添加或更新短信邮件模版",
            detail="<#if isAdd>添加<#if fl>成功<#else>失败</#if><#else>更新<#if fl>成功<#else>失败</#if></#if>短信邮件模版【templateId】"
    )
    @ResponseBody
    public ResultData save(SysTemplate sysTemplate) {
        if (StringUtil.isEmpty(sysTemplate.getTemplateId())) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            sysTemplate.setTemplateId(UUIDUtils.getUUIDFor32());
            sysTemplate.setIsDefault(0);
            SysAuditThreadLocalHolder.putParamerter("templateId", sysTemplate.getTemplateId());
            try {
                sysTemplateService.add(sysTemplate);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("save.success");
            } catch (Exception e) {
                SysAuditThreadLocalHolder.putParamerter("fl", false);
                return getResultDataError("save.failure");
            }
        } else {
            SysAuditThreadLocalHolder.putParamerter("templateId", sysTemplate.getTemplateId());
            SysAuditThreadLocalHolder.putParamerter("isAdd", false);
            try {
                sysTemplateService.update(sysTemplate);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("update.success");
            } catch (Exception e) {
                SysAuditThreadLocalHolder.putParamerter("fl", false);
                return getResultDataSuccess("update.failure");
            }
        }
    }

    /**
     * 导出系统模板xml。
     *
     * @param request request
     * @param response response
     * @throws Exception Exception
     */
    @RequestMapping("/exportXml")
    @Action(description = "导出短信邮件模板", detail = "导出短信邮件模板<#if fn>成功<#else>失败</#if>")
    public void exportXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] ids = RequestUtil.getStringAryByStr(request, "ids");
        if (BeanUtils.isNotEmpty(ids)) {
            String fileName = "SysTemplate_" + DateFormatUtil.getNowByString("yyyyMMddHHmmss") + ".xml";
            String strXml = sysTemplateService.exportXml(ids);
            FileUtil.downLoad(request, response, strXml, fileName);
        }
    }


    /**
     * 操作导入短信邮件模板页面
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/importXml")
    @Action(description = "操作导入短信邮件模板页面",detail="操作导入短信邮件模板页面")
    public String importXmlView(){
        return getAutoView();
    }

    /**
     * 导入系统模板XML
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/importXml")
    @Action(description = "导入短信邮件模板", detail = "导入短信邮件模板<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData importXml(MultipartHttpServletRequest request){
        MultipartFile fileLoad = request.getFile("file");
        boolean clearAll = RequestUtil.getBoolean(request, "clearAll", false);
        boolean setDefault = RequestUtil.getBoolean(request, "setDefault", false);
        if(null==fileLoad){
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("file.importXml.failure");
        }
        try {
            sysTemplateService.importXml(fileLoad.getInputStream(),clearAll,setDefault);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("file.importXml.success");
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("file.importXml.failure",1,e.getMessage());
        }
    }

    /**
     * 信息模板选择框页面
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/dialog")
    @Action(description = "操作信息模板选择框页面",detail="操作信息模板选择框页面")
    public String viewDialog(){
        return getAutoView();
    }

    /**
     * 校验短信邮件模板的名称唯一性
     * @param request
     * @return 返回结果
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/checkRepeatName")
    @Action(description="检查模板的名称有没有重复",detail = "模板的名称<#if success>可以使用<#else>已经存在，不可用</#if>")
    @ResponseBody
    public ResultData checkRepeatName(HttpServletRequest request) {
        String id=RequestUtil.getString(request, "id", "");
        String name=RequestUtil.getString(request, "name", "");
        //名称是否为空
        if("".equals(name)){
            return getResultDataError("script.name.null");
        }else{
            boolean isRepeatName = sysTemplateService.checkRepeatName(id,name);
            //名称是否已存在
            if(isRepeatName){
                SysAuditThreadLocalHolder.putParamerter("success",true);
                return getResultDataSuccess("script.name.success");
            }else{
                SysAuditThreadLocalHolder.putParamerter("success",false);
                return getResultDataError("script.name.failure");
            }
        }
    }

}
